<template>
  <el-dialog :title="title" :visible.sync="visible" width="500px" append-to-body @close="cancel">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="选手" prop="playerId">
        <el-select 
          v-model="form.playerId" 
          placeholder="请选择选手" 
          style="width: 100%" 
          :disabled="form.id !== undefined"
        >
          <el-option
            v-for="item in playerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="聊天室名" prop="roomName">
        <el-input v-model="form.roomName" placeholder="请输入聊天室名称" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "EditDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ""
    },
    playerOptions: {
      type: Array,
      default: () => []
    },
    data: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {
        id: undefined,
        playerId: undefined,
        roomName: ""
      },
      rules: {
        playerId: [
          { required: true, message: "选手不能为空", trigger: "change" }
        ],
        roomName: [
          { required: true, message: "聊天室名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    data: {
      handler(val) {
        if (val) {
          this.form = { ...val };
        }
      },
      immediate: true
    }
  },
  methods: {
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$emit("submit", this.form);
        }
      });
    },
    cancel() {
      this.reset();
      this.$emit("update:visible", false);
    },
    reset() {
      this.form = {
        id: undefined,
        playerId: undefined,
        roomName: ""
      };
      this.$nextTick(() => {
        this.$refs["form"]?.resetFields();
      });
    }
  }
};
</script> 